<?php
/**
 * Created by PhpStorm.
 * User: qttx
 * Date: 2019/5/30
 * Time: 13:56
 */
namespace app\api\controller;


use app\api\model\BuyorderModel;
use app\api\model\SettingModel;
use app\api\model\UserModel;
use app\api\model\XstModel;
use think\Db;

class Buyorder extends BaseController
{
    public function __construct()
    {
        parent::__construct();
        $this->buyorder = new BuyorderModel();
        $this->user = new UserModel();
        $this->setting = new SettingModel();
    }

    /**会员买单*/
    public function mumberbuy_index()
    {
        $data['bo.type'] = request()->post('type');
        $data['bo.member'] = 1;
        $data['bo.status'] = ['eq',1];
        $page = request()->post('page');
        if($data['bo.type']==1)
        {
            $mumberbuy_index = $this->buyorder->buyorder($data,$page);
        }else{
            $mumberbuy_index = $this->buyorder->sellorder($data,$page);
        }
        AjaxReturn('1', '成功', ['data' => $mumberbuy_index]);
    }

    /**商户买单*/
    public function buy_index()
    {
        $data['bo.type'] = request()->post('type');
        $data['bo.member'] = 2;
        $data['bo.status'] = ['eq',1];
        $page = request()->post('page');
        if($data['bo.type']==1)
        {
            $buy_index = $this->buyorder->buyorder($data,$page);
        }else{
            $buy_index = $this->buyorder->sellorder($data,$page);
        }

        AjaxReturn('1', '成功', ['data' => $buy_index]);
    }

    /**用户全部单*/
    public function member_index()
    {
        $data['uid'] = $this->uid;
        $page = request()->post('page');
        $sell_index = $this->buyorder->buyorder($data,$page);

        AjaxReturn('1', '成功', ['data' => $sell_index]);
    }

    /**用户已完成单*/
    public function complete_index()
    {
        $data['uid'] = $this->uid;
        $data['status'] = 4;
        $page = request()->post('page');
        $sell_index = $this->buyorder->buyorder($data,$page);

        AjaxReturn('1', '成功', ['data' => $sell_index]);
    }


    /**是否设置支付密码**/
    public function paypwd()
    {
        $data['id'] = $this->uid;
        $paypwd=$this->buyorder->paypwd($data);

        if($paypwd['pay_pwd'])
        {
            AjaxReturn('1','有密码');
        }else{
            AjaxReturn('0','无密码');
        }

    }
  
  	/**是否设置微信、支付宝、银行卡**/
    public function payway()
    {
        $uid = $this->uid;
        $type = request()->post('type');
        if($type==1)
        {
            $data = Db::name('wechat')->where('uid',$uid)->find();
        }elseif ($type==2)
        {
            $data = Db::name('alipay')->where('uid',$uid)->find();
        }elseif ($type==3)
        {
            $data = Db::name('bank')->where('uid',$uid)->find();
        }
        if($data)
        {
            AjaxReturn('1','已绑定');
        }else{
            AjaxReturn('0','未绑定');
        }
    }

    /**添加支付密码**/
    public function paypwd_update()
    {
        $data['id'] = $this->uid;
        $pay_pwd = request()->post('pay_pwd');
        $add['pay_pwd'] = authcode($pay_pwd,'ENCODE');
        $paypwd_update = $this->buyorder->paypwd_update($data,$add);

        if($paypwd_update)
        {
            AjaxReturn('1','添加成功');
        }else{
            AjaxReturn('0','添加失败');
        }

    }

    /**买单发布**/
    public function buyorder_add()
    {
        $add['number'] = abs(request()->post('number'));
        //if($add['number']%500!=0)
        //{
        //    AjaxReturn('101','挂单金额必须为500的倍数');
        //}
        if ($add['number'] == "" || !is_numeric($add['number']) || $add['number'] <= 0) {
            AjaxReturn('102','请输入正确的交易数量');
        }

        $add['uid'] = $this->uid;
        //判断上次交易是否完成
        $point = $this->buyorder
                ->where('to_uid',$this->uid)
          		->where('uid',$this->uid)
                ->where('status',[['=',1],['=',2],['=',3]],'or')
                ->find();
        if (!empty($point)) {
//            parent::error("106", "您有交易尚未完成！");
            AjaxReturn('103','您有交易尚未完成');
        }
        $pay_pwd = request()->post('pay_pwd');
        $user_pwd = $this->user->where('id',$this->uid)->find();
        if(authcode($user_pwd['pay_pwd'],'DECODE') != $pay_pwd)
        {
            AjaxReturn('104','您输入的支付密码不正确');
        }
        $data['id'] = $add['uid'];
        $user=Db::name('user')->where($data)->find();
        $add['name'] = $user['nickname'];
        $add['order_number'] = date("YmdHis",time()).time(). mt_rand(999, 9999);
        $add['way'] = request()->post('way');
        $add['pay_time'] = request()->post('pay_time');
        if ($user_pwd['type'] == 1)
        {
            $circulate = $this->setting->setting(9);
        }else{
            $circulate = $this->setting->setting(10);
        }
        $add['money'] = $add['number']*$circulate['value'];//计算
        $add['status'] = '1';
        $add['type'] = '1';
        $add['member'] = request()->post('member');
        $add['createtime'] = time();

        $buyorder_add = $this->buyorder->buyorder_add($add);

        if($buyorder_add)
        {
            AjaxReturn('1','成功');
        }else{
            AjaxReturn('0','失败');
        }


    }

    /**订单详情*/
    public function buylist()
    {
        $data['id'] = request()->post('id');
        $buylist = $this->buyorder->buylist($data);
      	$user = Db::name('user')->where('id',$buylist['uid'])->find();
        $buylist['phone'] = $user['phone'];
        if($buylist['status']==2)
        {
            $way = explode(',',$buylist['way']);
            $pay_way = [];
            foreach ($way as $k=>$value)
            {
                if($value == 1)
                {
                    $wechat = Db::name('wechat')->field('qrcode')->where('uid',$buylist['to_uid'])->find();
                    if($wechat)
                    {
                        $buylist['wechat']=$wechat['qrcode'];
                    }else{
                        $buylist['wechat']='';
                    }
                }
                if($value == 2)
                {
                    $alipay = Db::name('alipay')->field('qrcode')->where('uid',$buylist['to_uid'])->find();
                    if($alipay)
                    {
                        $buylist['alipay']=$alipay['qrcode'];
                    }else{
                        $buylist['alipay']='';
                    }
                }
                if($value == 3)
                {
                    $bank = Db::name('bank')->field('number')->where('uid',$buylist['to_uid'])->find();
                    if($bank)
                    {
                        $buylist['bank']=$bank['number'];
                    }else{
                        $buylist['bank']='';
                    }
                }
            }
        }
        $order_number = substr($buylist['order_number'],-4,4);
        $buylist['order_numbers']='**********'.$order_number;
            switch ($buylist['pay_time']) {
                case "1":
                    $buylist['pay_time'] = "30分钟";
                    break;
                case "2":
                    $buylist['pay_time'] = "60分钟";
                    break;
                case "3":
                    $buylist['pay_time'] = "90分钟";
                    break;
                case "4":
                    $buylist['pay_time'] = "120分钟";
                    break;
            }
      		if($buylist['type']==1)
            {
              switch ($buylist['status']) {
                  case "1":
                      $buylist['statuss'] = "确认卖出";
                      break;
                  case "2":
                      $buylist['statuss'] = "待付款";
                      break;
                  case "3":
                      $buylist['statuss'] = "待确认";
                      break;
                  case "4":
                      $buylist['statuss'] = "已完成";
                      break;
                  case "5":
                      $buylist['statuss'] = "撤回";
                      break;
              }
            }else{
              switch ($buylist['status']) {
                  case "1":
                      $buylist['statuss'] = "我要买";
                      break;
                  case "2":
                      $buylist['statuss'] = "待付款";
                      break;
                  case "3":
                      $buylist['statuss'] = "待确认";
                      break;
                  case "4":
                      $buylist['statuss'] = "已完成";
                      break;
                  case "5":
                      $buylist['statuss'] = "撤回";
                      break;
              }
            }

        AjaxReturn('1', '成功', ['data' => $buylist]);
    }

    /**买单匹配确认待付款**/
    public function buyorder_update()
    {
        $data['id'] = request()->post('id');
        $add['to_uid'] = $this->uid;//匹配人ID
        $user['id'] = $add['to_uid'];
        $user=Db::name('user')->where($user)->find();
        $add['to_name'] = $user['nickname'];
        $add['status'] = '2';
        $add['updatetime'] = time();
        $res = $this->buyorder->where($data)->find();
        if($res['uid']==$this->uid)
        {
            AjaxReturn('0','不能匹配自己的订单');
        }
      	$way = explode(',',$res['way']);
        foreach ($way as $k=>$value)
        {
            if($value == 1)
            {
                $ways = Db::name('wechat')->where('uid',$this->uid)->find();
                if(empty($ways))
                {
                    AjaxReturn('0','请先前往我的收款账户绑定账户');
                }
            }
            if($value == 2)
            {
                $ways = Db::name('alipay')->where('uid',$this->uid)->find();
                if(empty($ways))
                {
                    AjaxReturn('0','请先前往我的收款账户绑定账户');
                }
            }
            if($value == 3)
            {
                $ways = Db::name('bank')->where('uid',$this->uid)->find();
                if(empty($ways))
                {
                    AjaxReturn('0','请先前往我的收款账户绑定账户');
                }
            }
        }
       $point = $this->buyorder
                ->where('to_uid',$this->uid)
          		->where('uid',$this->uid)
                ->where('status',[['=',1],['=',2],['=',3]],'or')
                ->find();
        if (!empty($point)) {
//            parent::error("106", "您有交易尚未完成！");
            AjaxReturn('103','您有交易尚未完成,无法匹配新订单');
        }
      	$list['uid'] = $this->uid;
        $balance_list = $this->buyorder->balance_list($list);//查询用户余额
        if ($res['number'] > $balance_list['circulate']) {
            AjaxReturn('0', '余额不足');
        }
        $buyorder_add = $this->buyorder->buyorder_update($data,$add);
		$status = $this->buyorder->where($data)->find();
        if($buyorder_add)
        {
            AjaxReturn('1','成功',$status);
        }else{
            AjaxReturn('0','失败');
        }
    }

    /**待确认**/
    public function buyorder_confirm()
    {
        $data['id'] = request()->post('id');
      	$uid = $this->uid;
        $buylist = $this->buyorder->buylist($data);
        if ($buylist['status'] == 2&&$buylist['to_uid']==$uid) {
            AjaxReturn('108','对方未打款您无法确认收款');
        }
        $add['status'] = '3';
        $add['updatetime'] = time();

        $buyorder_confirm = $this->buyorder->buyorder_update($data,$add);

        if($buyorder_confirm)
        {
            AjaxReturn('1','成功');
        }else{
            AjaxReturn('0','失败');
        }
    }

    /**买单已完成**/
    public function buyorder_complete()
    {
      	$Xst = new XstModel();
        Db::startTrans();
        $data['id'] = request()->post('id');
        $uid = $this->uid;
        $buylist = $this->buyorder->buylist($data);
        if ($buylist['status'] == 3&&$buylist['uid']==$uid) {
            AjaxReturn('108','请等待对方确认');
        }
        $add['status'] = '4';
        $add['updatetime'] = time();

        $buyorder_confirm = $this->buyorder->buyorder_update($data,$add);//买卖单修改为完成状态

        /***买单用户流水表*/
        $data['id'] = request()->post('id');
        $buylist = $this->buyorder->buylist($data);//查询买卖单详情

        $uid = $buylist['uid'];
        $balance = $buylist['number'];

        $list['uid'] = $buylist['uid'];
        $balance_list = $this->buyorder->balance_list($list);//查询用户余额
        //获取买单人的钱包地址
        $from_info = $this->user->where('id',$uid)->find();

        $before_frozen = $balance_list['frozen'];
        //冻结币
        $frozen = round((($balance_list['circulation']+$balance)*2),4);
      	
        $direct = direct($uid);
        //添加释放表
        $release = release($buylist['uid'],$data['id'],$frozen,$balance,1);

        $upds['frozen'] = $balance_list['frozen']+$frozen;
        $balance_updates = $this->buyorder->balance_update($list,$upds);//修改用户冻结币

        $later_frozen = $upds['frozen'];

        $buy_logs =$this->buyorder->Log($uid,4,$frozen,4,1,$before_frozen,$later_frozen,'买单买入'.$frozen.'币');//买单用户冻结币写入流水表
        $accelerate = accelerate($uid,$balance,1);

        /***卖单用户流水表*/
        $datas['id'] = request()->post('id');
        $buylists = $this->buyorder->buylist($datas);//查询买卖单详情

        $uids = $buylists['to_uid'];
        $balance_types = '1';
        $balances = $buylists['number'];
        $types = '5';
        $signs = '0';

        $lists['uid'] = $buylists['to_uid'];
        $balance_lists = $this->buyorder->balance_list($lists);//查询用户余额
		//获取卖单用户的钱包地址
        $user_info = $this->user->where('id',$uids)->find();
      	$eth_yue = $Xst->getbalance($user_info['xst_address']);
        if($eth_yue < ($balances * 0.00000006)){
            AjaxReturn('0','您的ETH币不足');
        }
      	
        $before_balances = $balance_lists['circulate'];

        $upds['circulate'] =  $balance_lists['circulate']-$buylists['number'];
        $sell_update = $this->buyorder->balance_update($lists,$upds);//修改用户流通币

        $later_balances = $upds['circulate'];
        $messages = '卖单扣除'.$buylists['number'].'币';

        $sell_log =$this->buyorder->Log($uids,$balance_types,$balances,$types,$signs,$before_balances,$later_balances,$messages);//卖单用户写入流水表
		//$res = $Xst->transfer($user_info['xst_address'],$privateKeys=$user_info['xst_key'],$value=$balances,$from_info['xst_address'],$uids);
      	$res =1;
      
        if($buyorder_confirm&&$sell_update&&$sell_log&&$balance_updates&&$release&&$buy_logs&&$res&&$release&&$direct)
        {
            Db::commit();
            AjaxReturn('1','成功');
        }else{
            Db::rollback();
            AjaxReturn('0','失败');
        }
    }


    /**卖单发布**/
    public function sellorder_add()
    {
        Db::startTrans();
        $add['number'] = request()->post('number');
        if($add['number']%500!=0)
        {
            AjaxReturn('101','挂单金额必须为500的倍数');
        }
        if ($add['number'] == "" || !is_numeric($add['number']) || $add['number'] <= 0) {
            AjaxReturn('102','请输入正确的交易数量');
        }
        $list['uid'] = $this->uid;
        //判断上次交易是否完成
        $point = $this->buyorder
                ->where('to_uid',$this->uid)
          		->where('uid',$this->uid)
                ->where('status',[['=',1],['=',2],['=',3]],'or')
                ->find();
        if (!empty($point)) {

            AjaxReturn('103','您有交易尚未完成');

        }
        $balance_list = $this->buyorder->balance_list($list);//查询用户余额
        if ($add['number'] > $balance_list['circulate']) {
            AjaxReturn('0', '余额不足');
        } else {

            $add['to_uid'] = $this->uid;
            $data['id'] = $add['to_uid'];
            $user = Db::name('user')->where($data)->find();
            $add['to_name'] = $user['nickname'];
            $add['order_number'] = date("YmdHis", time()) . time() . mt_rand(999, 9999);

            $add['way'] = request()->post('way');
            $add['pay_time'] = request()->post('pay_time');
            $circulate = $this->setting->setting(5);
        	$add['money'] = $add['number']*$circulate['value'];//计算
            $add['status'] = '1';
            $add['type'] = '2';
            $add['member'] = request()->post('member');
            $add['createtime'] = time();

            $buyorder_add = $this->buyorder->buyorder_add($add);


            /***卖单用户流水表*/
            $uids = $this->uid;
            $balance_types = '1';
            $balances = request()->post('number');
            $types = '5';
            $signs = '0';

            $lists['uid'] = $uids;
            $balance_lists = $this->buyorder->balance_list($lists);//查询用户余额

            $before_balances = $balance_lists['circulate'];

            $upds['circulate'] =  $balance_list['circulate']-$add['number'];
            $sell_update = $this->buyorder->balance_update($lists,$upds);//修改用户余额

            $later_balances = $upds['circulate'];
            $messages = '卖单扣除'.$balances.'币';

            $sell_log =$this->buyorder->Log($uids,$balance_types,$balances,$types,$signs,$before_balances,$later_balances,$messages);//卖单用户写入流水表


            if ($buyorder_add&&$sell_update&&$sell_update&&$sell_log) {
                Db::commit();
                AjaxReturn('1', '成功');
            } else {
                Db::rollback();
                AjaxReturn('0', '失败');
            }
        }
    }


        /**卖单匹配确认待付款**/
        public function sellorder_update()
        {
            $data['id'] = request()->post('id');
            $add['uid'] = $this->uid;
            $user['id'] = $add['uid'];
            $user=Db::name('user')->where($user)->find();
            $add['name'] = $user['nickname'];
            $add['status'] = '2';
            $add['updatetime'] = time();
            $res = $this->buyorder->where($data)->find();
            if($res['to_uid']==$this->uid)
            {
                AjaxReturn('0','不能匹配自己的订单');
            }
            $point = $this->buyorder
                ->where('to_uid',$this->uid)
          		->where('uid',$this->uid)
                ->where('status',[['=',1],['=',2],['=',3]],'or')
                ->find();
            if (!empty($point)) {
    //            parent::error("106", "您有交易尚未完成！");
                AjaxReturn('103','您有交易尚未完成,无法匹配新订单');
            }
            $buyorder_add = $this->buyorder->buyorder_update($data,$add);

            if($buyorder_add)
            {
                AjaxReturn('1','成功');
            }else{
                AjaxReturn('0','失败');
            }
        }
	
  	/**卖单待确认**/
    public function sellorder_confirm()
    {
        $data['id'] = request()->post('id');
        $uid = $this->uid;
        $buylist = $this->buyorder->buylist($data);
        if ($buylist['status'] == 2&&$buylist['to_uid']==$uid) {
            AjaxReturn('108','对方未打款您无法确认收款');
        }
        $add['status'] = '3';
        $add['updatetime'] = time();

        $buyorder_confirm = $this->buyorder->buyorder_update($data,$add);

        if($buyorder_confirm)
        {
            AjaxReturn('1','成功');
        }else{
            AjaxReturn('0','失败');
        }
    }

    /**卖单已完成**/
    public function sellorder_complete()
    {
        Db::startTrans();
        $uid = $this->uid;
        $data['id'] = request()->post('id');

        $buylist = $this->buyorder->buylist($data);
        if ($buylist['status'] == 3&&$buylist['uid']==$uid) {
            AjaxReturn('108','请等待对方确认');
        }
        $add['status'] = '4';
        $add['updatetime'] = time();

        $buyorder_confirm = $this->buyorder->buyorder_update($data,$add);//买卖单修改为完成状态

        /***买单用户流水表*/
        $data['id'] = request()->post('id');
        $buylist = $this->buyorder->buylist($data);//查询买卖单详情

        $uid = $buylist['uid'];
        $balance = $buylist['number'];
        $circulation = round(($balance*2*0.25),4);
        $frozen = round(($balance*2*0.75),4);
        $list['uid'] = $buylist['uid'];
        $balance_list = $this->buyorder->balance_list($list);//查询用户余额

        $before_balance = $balance_list['circulation'];
        $before_frozen = $balance_list['frozen'];

        $upd['circulation'] = $balance_list['circulation']+$circulation;
        $balance_update = $this->buyorder->balance_update($list,$upd);//修改用户循环币
        $upds['frozen'] = $balance_list['frozen']+$frozen;
        $balance_updates = $this->buyorder->balance_update($list,$upds);//修改用户冻结币

        $release = Db::name('release')->insert(['uid'=>$uid,'release'=>$frozen,'releasetime'=>0,'createtime'=>time()]);

        $later_balance = $upd['circulation'];
        $later_frozen = $upds['frozen'];
        $message = '买单买入'.$buylist['number'].'币';

        $buy_log =$this->buyorder->Log($uid,2,$circulation,4,1,$before_balance,$later_balance,$message);//买单用户循环币写入流水表
        $buy_logs =$this->buyorder->Log($uid,4,$frozen,4,1,$before_frozen,$later_frozen,'买单买入'.$buylist['number'].'币');//买单用户冻结币写入流水表

        if($buyorder_confirm&&$balance_update&&$buy_log&&$balance_updates&&$release&&$buy_logs)
        {
            Db::commit();
            AjaxReturn('1','成功');
        }else{
            Db::rollback();
            AjaxReturn('0','失败');
        }
    }

	//我的订单
    public function mylist()
    {
        $type = request()->post('type');
      	$page = request()->post('page');
        $where = 1;
        $uid = $this->uid;
        if($type==1)
        {
            $where .= " and bo.uid=". $uid;
        }elseif ($type == 2)
        {
            $where .= " and bo.to_uid=". $uid;
        }elseif ($type == 3)
        {
            $where .= " and (bo.to_uid=". $uid ." or bo.uid=". $uid .") and bo.status=4";
        }elseif ($type == 4)
        {
            $where .= " and bo.status=5";
        }
        $list = $this->buyorder->field('bo.*,u.Picture')->alias('bo')->join('xst_user u','bo.uid = u.id')->where($where)->order('createtime', 'desc')->limit(0,$page*10)->select();
        foreach ($list as $key=>$val)
        {
            $order_number = substr($val['order_number'],-4,4);
            $list[$key]['order_numbers']='**************'.$order_number;
            //$buyorder[$key]['way'] = explode(',',$val['way']);
        }
        if($list)
        {
            AjaxReturn('1','成功',$list);
        }else{
            AjaxReturn('0','暂无更多数据');
        }
    }
  
      /**用户申诉单*/
       public function buyorder_appeal()
    {
        $data['id'] = request()->post('id');
        $add['status'] = '5';
        $add['content'] = request()->post('content');
        if($add['content'])
        {
            AjaxReturn('0','申诉内容不能为空！');
        }else{
           
        $buyorder_appeal = $this->buyorder->buyorder_update($data,$add);

        if($buyorder_appeal)
        {
            AjaxReturn('1','成功');
        }else{
            AjaxReturn('0','失败');
        }
       }
    }



}
